package com.whiteblue.model;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.whiteblue.config.CFG;
import com.whiteblue.tool.HTTPParam;
import com.whiteblue.tool.HttpUtil;
import com.whiteblue.tool.Model;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by WhiteBlue on 15/4/5.
 */
public class Book extends Model<Book> {
    public static final Book dao = new Book();

    private static final String BOOK_CACHE = "book";
    private static final String BOOK_LIST_CACHE = "book_list";
    private static final String INDEX_LIST_CACHE = "index_list";
    private static final String MY_LIST_CACHE = "my_list";

    private static final String MESSAGE_INT_CACHE = "msg_int";
    private static final String MESSAGE_LIST_CACHE = "msg_list";


    public Book() {
        super(BOOK_CACHE);
    }

    public Book getById(int id) {
        return loadModel(id);
    }

    public User getUser() {
        return User.dao.getById(this.getInt("userId"));
    }

    public List<Book> findAll(String name) {
        return loadModelList(dao.find("select id from b_book where name like '%" + name + "%' limit 10"));
    }

    public Page<Book> getForCategory(int categoryId, int pageNumber) {
        return loadModelPage(dao.paginateByCache(BOOK_LIST_CACHE, categoryId, pageNumber, CFG.page_size, "select id", "from b_book where category = ? order by time desc", categoryId));
    }

    public void addBook(int type, int category, String method, int price, int userId, String contact) {
        this.set("type", type).set("category", category).set("method", method).set("price", price);
        this.set("userId", userId).set("time", new Date()).set("contact", contact);
        this.save();
        clearCache();
    }

    public List<Book> getForIndex() {
        return loadModelList(dao.findByCache(INDEX_LIST_CACHE, 0, "select id from b_book order by time desc limit 8"));
    }

    public boolean getFromDOUBAN(String ISBN) {
        try {
            List<HTTPParam> list = new ArrayList<HTTPParam>();
            String back = HttpUtil.sendGet("https://api.douban.com/v2/book/isbn/:" + ISBN, list);
            JSONObject jsonObj = JSONObject.fromObject(back);
            Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObj, Map.class);
            List<String> authors = (List<String>) map.get("author");
            String author = "";
            for (int i = 0; i < authors.size(); i++) {
                if (i == 0) {
                    author = authors.get(i);
                } else {
                    author += "," + authors.get(i);
                }
            }
            this.set("name", map.get("title")).set("content", map.get("summary")).set("img", map.get("image"));
            this.set("author", author).set("publish", map.get("publisher")).set("ISBN",map.get("isbn13"));
            return true;
        } catch (IOException e) {
            return false;
        }
    }


    public void setRead(int bookId){
        Book book=this.getById(bookId);
        book.set("hasMsg",1);
        book.update();
        this.clearMsgCache();
    }

    public void readClear(){
        this.set("hasMsg",0);
        this.update();
        this.clearMsgCache();
    }


    public Page<Book> getForUser(int userId, int page) {
        return loadModelPage(paginateByCache(MY_LIST_CACHE, userId, page, CFG.page_size, "select id ", "from b_book where userId = ?", userId));
    }

    public int findMsg(int userId) {
        List<Book> list = this.findByCache(MESSAGE_INT_CACHE, userId, "select id from b_book where hasMsg = 1 and userId = ?", userId);
        if (list.size() > 99) {
            return 99;
        } else {
            return list.size();
        }
    }

    public Page<Book> getMsgList(int userId, int page) {
        return loadModelPage(this.paginateByCache(MESSAGE_LIST_CACHE, userId, page, CFG.page_size, "select id", "from b_book where hasMsg = 1 and userId = ?", userId));
    }

    public Category getCategory() {
        return Category.dao.getById(this.getInt("category"));
    }

    private void clearCache() {
        CacheKit.removeAll(BOOK_LIST_CACHE);
        CacheKit.removeAll(INDEX_LIST_CACHE);
        CacheKit.removeAll(MY_LIST_CACHE);
    }

    private void clearAllCache() {
        CacheKit.removeAll(BOOK_CACHE);
        CacheKit.removeAll(BOOK_LIST_CACHE);
        CacheKit.removeAll(INDEX_LIST_CACHE);
        CacheKit.removeAll(MY_LIST_CACHE);
    }

    public void clearMsgCache(){
        CacheKit.removeAll(MESSAGE_INT_CACHE);
        CacheKit.removeAll(MESSAGE_LIST_CACHE);
    }

    public void deleteMe(){
        this.delete();
        clearAllCache();
    }

}
